﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RESP_IIWaterAssessment
{
    public partial class FarmIndicatorsForm : Form
    {
        public FarmIndicatorsForm()
        {
            InitializeComponent();
        }

        int regID, avpID, fhID = -1, cultID, year = DateTime.Now.Year;
        tb_farmIndicator farmIndicator;

        private void FarmIndicatorsForm_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }
            cbYear.SelectedIndex = cbYear.FindStringExact(DateTime.Now.Year.ToString());

            cbCulture.SelectedIndexChanged -= cbCulture_SelectedIndexChanged;
            cbCulture.DataSource = UtilClass.GetCBCultureDataSourse();
            cbCulture.DisplayMember = "Name";
            cbCulture.ValueMember = "ID";
            cbCulture.SelectedIndex = -1;
            cbCulture.SelectedIndexChanged += new EventHandler(cbCulture_SelectedIndexChanged);
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.Enabled = true;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbFH.DataSource = null;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);

            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
                cbFH.SelectedIndexChanged -= cbFH_SelectedIndexChanged;
                cbFH.Enabled = true;
                cbFH.DataSource = DBClass.Farms
                    .Where(wh => wh.AVPID == avpID)
                    .Select(se => new { ID = se.ID, Name = se.Name })
                    .OrderBy(o => o.Name)
                    .ToArray();
                cbFH.DisplayMember = "Name";
                cbFH.ValueMember = "ID";
                cbFH.SelectedIndex = -1;
                cbFH.Text = string.Empty;
                cbFH.SelectedIndexChanged += new EventHandler(cbFH_SelectedIndexChanged);
            }
        }

        private void cbFH_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbFH.SelectedIndex >= 0)
            {
                fhID = Convert.ToInt32(cbFH.SelectedValue);
            }
            else
                fhID = 0;

            if (fhID > 0 && cultID > 0 && year > 0)
                ShowFarmIndicator(fhID, cultID, year);
        }

        private void cbCulture_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCulture.SelectedIndex >= 0)
            {
                cultID = Convert.ToInt32(cbCulture.SelectedValue);
            }
            else
                cultID = 0;

            if (fhID > 0 && cultID > 0 && year > 0)
                ShowFarmIndicator(fhID, cultID, year);
        }

        private void ShowFarmIndicator(int fID, int cID, int yr)
        {
            farmIndicator = DBClass.FarmIndicators
                .Where(wh => wh.CultureID == cID && wh.Date.Year == yr && wh.FarmID == fID)
                .SingleOrDefault();
            if (farmIndicator != null)
            {
                tbAgricultureLoss.Text = farmIndicator.AgricultureLoss.Value.ToString();
                tbHarvestCost.Text = farmIndicator.HarvestCost.Value.ToString();
                tbHarvestQuantity.Text = farmIndicator.HarvestQuantity.Value.ToString();
                tbInvestment.Text = farmIndicator.Investment.Value.ToString();
                tbProfitability.Text = farmIndicator.Profitability.Value.ToString();
                tbTax.Text = farmIndicator.Tax.Value.ToString();
                tbWaterQuantity.Text = farmIndicator.WaterQuantity.Value.ToString();
            }
            else
            {
                tbWaterQuantity.Text = tbTax.Text = tbProfitability.Text = tbInvestment.Text =
                    tbHarvestQuantity.Text = tbHarvestCost.Text = tbAgricultureLoss.Text = string.Empty;
            }
        }

        private void buttonAccept_Click(object sender, EventArgs e)
        {
            decimal WatQ, HarQ, HarC, AgrLoss, tax, profit, invest;
            if (tbAgricultureLoss.Text.GetDecimalOrDefault(out AgrLoss) &&
                tbHarvestCost.Text.GetDecimalOrDefault(out HarC) &&
                tbHarvestQuantity.Text.GetDecimalOrDefault(out HarQ) &&
                tbInvestment.Text.GetDecimalOrDefault(out invest) &&
                tbProfitability.Text.GetDecimalOrDefault(out profit) &&
                tbTax.Text.GetDecimalOrDefault(out tax) &&
                tbWaterQuantity.Text.GetDecimalOrDefault(out WatQ) &&
                fhID > 0 && cultID > 0 && year >= 1991)
            {
                if (farmIndicator == null)
                {
                    farmIndicator = new tb_farmIndicator
                    {
                        AgricultureLoss = AgrLoss,
                        CultureID = cultID,
                        Date = new DateTime(year, 1, 1),
                        FarmID = fhID,
                        HarvestCost = HarC,
                        HarvestQuantity = HarQ,
                        Investment = invest,
                        Profitability = profit,
                        Tax = tax,
                        WaterQuantity = WatQ
                    };
                    DBClass.FarmIndicators.InsertOnSubmit(farmIndicator);
                }
                else
                {
                    farmIndicator.WaterQuantity = WatQ;
                    farmIndicator.Tax = tax;
                    farmIndicator.Profitability = profit;
                    farmIndicator.Investment = invest;
                    farmIndicator.HarvestQuantity = HarQ;
                    farmIndicator.HarvestCost = HarC;
                    farmIndicator.AgricultureLoss = AgrLoss;
                }
                try
                {
                    DBClass.RESPContext.SubmitChanges();
                    MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                }
                catch
                {
                    MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                }
            }
            else
            {
                MessageBox.Show("Не корректно заполненны данные");
                return;
            }

            string msg = InformationClass.Lang ? "Изменения успешно внесены. Закрыть форму?" : "Ўзгартиришлар муваффақиятли киритилди. Шакл ёпилсинми?";
            if (MessageBox.Show(msg, msgClass.msgAchtung, MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                this.Close();
            }
        }

        private void cbYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            year = cbYear.SelectedIndex > 0 ? Convert.ToInt32(cbYear.Items[cbYear.SelectedIndex].ToString()) : 0;

            if (fhID > 0 && cultID > 0 && year > 0)
                ShowFarmIndicator(fhID, cultID, year);
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
